package com.ts.proj.json;

import com.ts.base.controller.BaseController;
import com.ts.common.constant.ConsoleConstant;
import com.ts.common.constant.Controller2FTLConstant;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.*;
import com.ts.proj.service.*;
import com.ts.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class SystemConfigJson extends BaseController {

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private SystemMenuService systemMenuService;

    @Autowired
    private SystemRoleService systemRoleService;

    @Autowired
    private SystemButtonService systemButtonService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SystemFieldService systemFieldService;

    @Autowired
    private SystemColumnService systemColumnService;

    @Autowired
    private SystemGlobalService systemGlobalService;

    @Autowired
    private TemplatePageService templatePageService;

    /**
     * 显示list
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/config-list/{page}/{size}")
    public Map<String,Object> localConstantList(@PathVariable("page") Integer page, @PathVariable("size") Integer size){

        HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        PageData pageData = this.getPageData();
        pageData.put("deleteFlag", "N");
        //用户权限
        if(user.getPowerLevel().equals("0")){
            pageData.put("userId", user.getId());
        }
        pageData.put("belongTo", user.getBelongTo());

        long count = systemConfigService.count(pageData);
        List<SystemConfigEntity> systemConfigEntities = systemConfigService.findAll(pageData,page-1,size);
        pageData.put("total",count);
        pageData.put("rows", systemConfigEntities);
        return pageData;
    }

    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/config-ins-upd-del/{id}")
    public Object logCreateUpdate(@PathVariable("id") String id){
        PageData pageData = this.getPageData();
        SystemConfigEntity systemConfigEntity = systemConfigService.findById(Integer.valueOf(id));
        //字段信息维护
        if(null!=pageData.get("entityName")&&!"".equals(pageData.get("entityName").toString())){
            systemConfigEntity.setEntityName(pageData.get("entityName").toString());
            //本目录名称Rout
            systemConfigEntity.setSelfMenuNameRout(StringsUtil.lowerCase(pageData.get("entityName").toString())+"-list");
            //表名
            systemConfigEntity.setTableName("ta_"+ StringsUtil.lowerCase(pageData.getString("entityName")));
        }
        //属性字段维护
        if(null!=pageData.get("entityAttribute")&&!"".equals(pageData.get("entityAttribute").toString())){
            systemConfigEntity.setEntityAttribute(pageData.get("entityAttribute").toString());
        }
        //此界面所对应的一级菜单
        if(null!=pageData.get("parentMenuNameKey")&&!"".equals(pageData.get("parentMenuNameKey").toString())){
            //此界面所对应的一级菜单
            Integer firstMenu = new Integer(0);
            //此界面所对应的二级菜单
            Integer secondMenu = new Integer(0);
            //如果是已有的，pageData.get("parentMenuNameKey")可以转成Integer,同时一级菜单不需要存入，只需存入二级菜单
            try {
                firstMenu = Integer.valueOf(pageData.get("parentMenuNameKey").toString());
                systemConfigEntity.setParentMenuNameKey(String.valueOf(firstMenu));
            } catch (NumberFormatException e) {
                //如果是新增的，pageData.get("parentMenuNameKey")不可以转成Integer，需要存入一级菜单
                //新增parentMenu
                SystemMenuEntity parentSystemMenuEntity = new SystemMenuEntity();
                parentSystemMenuEntity.setMenuName(pageData.get("parentMenuNameKey").toString());
                parentSystemMenuEntity.setMenuURL("#");
                parentSystemMenuEntity.setMenuIcon("Hui-iconfont-news");
                parentSystemMenuEntity.setParentId("0");
                systemMenuService.save(parentSystemMenuEntity);
                firstMenu = parentSystemMenuEntity.getId();
                systemConfigEntity.setParentMenuNameKey(String.valueOf(firstMenu));
            }
                //新增selfMenu

            SystemMenuEntity secondSystemMenuEntity = null;
            if(null!=systemConfigEntity.getSelfMenuId()&&!"".equals(systemConfigEntity.getSelfMenuId())){
                secondSystemMenuEntity = systemMenuService.findById(systemConfigEntity.getSelfMenuId());
            }else{
                secondSystemMenuEntity = new SystemMenuEntity();
            }
            secondSystemMenuEntity.setMenuName(pageData.get("selfMenuNameValue").toString());
            secondSystemMenuEntity.setMenuURL("business-"+ StringsUtil.lowerCase(pageData.get("entityName").toString())+"-list");
            secondSystemMenuEntity.setMenuIcon("#");
            secondSystemMenuEntity.setParentId(String.valueOf(firstMenu));
            systemMenuService.save(secondSystemMenuEntity);
            secondMenu = secondSystemMenuEntity.getId();

            systemConfigEntity.setParentMenuId(firstMenu);
            systemConfigEntity.setSelfMenuId(secondMenu);
        }
        //本目录名称Value
        if(null!=pageData.get("selfMenuNameValue")&&!"".equals(pageData.get("selfMenuNameValue").toString())){
            systemConfigEntity.setSelfMenuNameValue(pageData.get("selfMenuNameValue").toString());
        }
        if(null!=pageData.get("deleteFlag")&&"Y".equals(pageData.get("deleteFlag").toString())){
            systemConfigEntity.setDeleteFlag(InsUpdDelFlagConstant.DELETE_FLAG_Y);
            SystemMenuEntity delete = systemMenuService.findById(systemConfigEntity.getSelfMenuId());
            delete.setDeleteFlag(InsUpdDelFlagConstant.DELETE_FLAG_Y);
            systemMenuService.save(delete);
        }
        systemConfigService.save(systemConfigEntity);
        return null;
    }

    /**
     * 生成文件
     */
    @RequestMapping("/config-generate/{id}")
    public void adminDownload(@PathVariable("id") String id){
        SystemConfigEntity sysconfEntity = systemConfigService.findById(Integer.valueOf(id));

        String developBasePath = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1).replaceAll("target/classes/","src/main/java/com/ts/proj/");
        String developBaseFTLPath = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1).replaceAll("target/classes/","src/main/resources/templates/business/");
        if((null!=sysconfEntity.getEntityName()&&!"".equals(sysconfEntity.getEntityName())&&(null!=sysconfEntity.getEntityAttribute()&&!"".equals(sysconfEntity.getEntityAttribute())))&&
                (null!=sysconfEntity.getTableName()&&!"".equals(sysconfEntity.getTableName()))){
            //实体名称
            String entityNameStr = sysconfEntity.getEntityName();
            //属性
            String[] entityAttrSplit = sysconfEntity.getEntityAttribute().split(";");
            String entityContent = "";
//            String excelEntityContent = "";
            for(int i=0;i<entityAttrSplit.length;i++){
                String temp = entityAttrSplit[i];
                //默认String
                String entityAttr = "";
                String entityAttrType = "";
                if(temp.split("_").length==1){
                    entityAttr = temp.split("_")[0];
                    entityAttrType = "String ";
                }else if (temp.split("_").length==2){
                    entityAttr = temp.split("_")[0];
                    entityAttrType = temp.split("_")[1];
                }
//                excelEntityContent += "\r\n\t@Excel(name=\""+entityAttr+"\")\r\tprivate "+entityAttrType+" "+entityAttr+";\n";
                entityContent += "\r\n\tprivate "+entityAttrType+" "+entityAttr+";\n";
            }
            //所有模板
            List<TemplatePage> allTemplatePage = templatePageService.findAll();
            //留一个口子
            // stringRedisTemplate.opsForValue().get(RedisKeyConstant.USERINFOREDISKEY);
            //第一步：生成所有页面
            for(TemplatePage templatePage :allTemplatePage){
                String outPutFileName = "";
                //输出名称为：**-list.ftl
                if(templatePage.getTemplatePageName().equals("FTL")){
                    outPutFileName += StringsUtil.lowerCase(entityNameStr) + "-list.ftl";
                    //输出名称：A*.java
                }else{
                    outPutFileName += entityNameStr + templatePage.getTemplatePageName() + ".java";
                }

                String templatePageContent = templatePage.getTemplatePageContent();
                String replace= templatePageContent.replaceAll("TEMPLAGEREPLACE", entityNameStr);
                replace = replace.replaceAll("LOWEREREPLACE", StringsUtil.lowerCase(entityNameStr));
                //TABLENAME,ATTRIBUTES主要是针对Entity
                replace = replace.replaceAll("TABLENAME", sysconfEntity.getTableName());
//                replace = replace.replaceAll("EXCELATTRIBUTES", excelEntityContent);
                replace = replace.replaceAll("ATTRIBUTES", entityContent);

                InputStream inputStream = new ByteArrayInputStream(replace.getBytes());
                try{
                    String path = Controller2FTLConstant.WINDOWPATH;
                    if(outPutFileName.endsWith("ftl")){
                        File ftlFileDir = new File(developBaseFTLPath+ StringsUtil.lowerCase(entityNameStr));
                        ftlFileDir.mkdir();
                        path = ftlFileDir.getPath();
                    }else if(outPutFileName.endsWith("Json.java")){
                        path = developBasePath + "" + Controller2FTLConstant.JSONPATH + "\\";
                    }else if(outPutFileName.endsWith("Controller.java")){
                        path = developBasePath + "" + Controller2FTLConstant.CONTROLLERPATH+ "\\";
                    }else if(outPutFileName.endsWith("Entity.java")){
                        path = developBasePath + "" + Controller2FTLConstant.ENTITYPATH + "\\";
                    }
//                    else if(outPutFileName.endsWith("EntityExcel.java")){
//                        path = developBasePath + "" + Controller2FTLConstant.ENTITYPATH + "\\excelEntity\\";
//                    }
                    else if(outPutFileName.endsWith("Repository.java")){
                        path = developBasePath + "" + Controller2FTLConstant.REPOSITORYPATH + "\\";
                    }else if(outPutFileName.endsWith("Service.java")){
                        path = developBasePath + "" + Controller2FTLConstant.SERVICEPATH + "\\";
                    }else if(outPutFileName.endsWith("ServiceImpl.java")){
                        path = developBasePath + "" + Controller2FTLConstant.IMPLPATH + "\\";
                    }
                    FileUpload.copyFile(inputStream, path, outPutFileName);
                }catch (IOException e){
                }
            }
//            //第二步：授权
            SystemConfigEntity byId = systemConfigService.findById(Integer.valueOf(id.toString()));
//            //获取菜单
            String rights = this.getRequest().getSession().getAttribute(ConsoleConstant.REALRIGHTS).toString();
            List<Integer> roleIds = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.ROLEID).toString(),List.class);
            List<String> ids = new ArrayList<>();
            ids.add(String.valueOf(byId.getParentMenuId()));
            ids.add(String.valueOf(byId.getSelfMenuId()));
            for(int i=0;i<200;i++){
                if (RightsHelper.testRights(rights.substring(1), i)) {
                    ids.add(String.valueOf(i));
                }
            }
            String[] idArray = ids.toArray(new String[ids.size()]);
            String newRights = "R"+String.valueOf(RightsHelper.sumRights(idArray));

            //第三步：生成按钮
            //
            PageData btnByMenuId = new PageData();
            btnByMenuId.put("menuID", byId.getSelfMenuId());
            List<SystemButtonEntity> systemButtonList = systemButtonService.findAll(btnByMenuId);
            Integer systemAddButtonId = new Integer(0);
            Integer systemEditButtonId = new Integer(0);
            Integer systemDeleteButtonId = new Integer(0);
            Integer systemCopyLineButtonId = new Integer(0);
            Integer systemDownLoadButtonId = new Integer(0);
            if(systemButtonList.size()==0){
                //新增
                SystemButtonEntity systemAddButton = new SystemButtonEntity(byId.getSelfMenuId(),"新增","icon-add","新增业务","add");
                systemAddButton.setCreateTime(DateUtil.getID());
                systemButtonService.save(systemAddButton);
                systemAddButtonId = systemAddButton.getId();
                //修改
                SystemButtonEntity systemEditButton = new SystemButtonEntity(byId.getSelfMenuId(),"修改","icon-edit","修改业务","edit");
                systemEditButton.setCreateTime(DateUtil.getID());
                systemButtonService.save(systemEditButton);
                systemEditButtonId = systemEditButton.getId();
                //删除
                SystemButtonEntity systemDeleteButton = new SystemButtonEntity(byId.getSelfMenuId(),"删除","icon-remove","删除业务","delete");
                systemDeleteButton.setCreateTime(DateUtil.getID());
                systemButtonService.save(systemDeleteButton);
                systemDeleteButtonId = systemDeleteButton.getId();
                //行复制
                SystemButtonEntity systemCopyButton = new SystemButtonEntity(byId.getSelfMenuId(),"行复制","icon-add","复制行项目","copy");
                systemCopyButton.setCreateTime(DateUtil.getID());
                systemButtonService.save(systemCopyButton);
                systemCopyLineButtonId = systemCopyButton.getId();
                //行复制
                SystemButtonEntity systemDownLoadButton = new SystemButtonEntity(byId.getSelfMenuId(),"下载","icon-download","下载","export");
                systemDownLoadButton.setCreateTime(DateUtil.getID());
                systemButtonService.save(systemDownLoadButton);
                systemDownLoadButtonId = systemDownLoadButton.getId();
            }else{
                for(SystemButtonEntity sb : systemButtonList){
                    if(sb.getButtonId().equals("add")){
                        systemAddButtonId = sb.getId();
                    }else if(sb.getButtonId().equals("edit")){
                        systemEditButtonId = sb.getId();
                    }else if(sb.getButtonId().equals("delete")){
                        systemDeleteButtonId = sb.getId();
                    }else if(sb.getButtonId().equals("copy")){
                        systemCopyLineButtonId = sb.getId();
                    }else if(sb.getButtonId().equals("download")){
                        systemDownLoadButtonId = sb.getId();
                    }
                }
            }
            String buttonRights = this.getRequest().getSession().getAttribute(ConsoleConstant.BUTTONRIGHTS).toString();
            List<String> btnIds = new ArrayList<>();
            btnIds.add(String.valueOf(systemAddButtonId));
            btnIds.add(String.valueOf(systemEditButtonId));
            btnIds.add(String.valueOf(systemDeleteButtonId));
            btnIds.add(String.valueOf(systemCopyLineButtonId));
            btnIds.add(String.valueOf(systemDownLoadButtonId));
            for(int i=0;i<2000;i++){
                if (RightsHelper.testRights(buttonRights.substring(1), i)) {
                    btnIds.add(String.valueOf(i));
                }
            }
            String[] btnIdsArray = btnIds.toArray(new String[btnIds.size()]);
            String newBtnRights = "B"+String.valueOf(RightsHelper.sumRights(btnIdsArray));

            SystemRoleEntity systemRole = systemRoleService.findById(roleIds.get(0));
            systemRole.setRights(newRights);
            systemRole.setBtnRights(newBtnRights);
            systemRole.setUpdateTime(DateUtil.getID());
            systemRoleService.save(systemRole);
        }
    }

    /**
     * 显示column
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/config-column-list/{page}/{size}")
    public Map<String,Object> configColumnList(@PathVariable("page") Integer page, @PathVariable("size") Integer size){
        PageData pageData = this.getPageData();
        pageData.put("deleteFlag", "N");
        long count = systemColumnService.count(pageData);
        List<SystemColumnEntity> systemConfigs = systemColumnService.findAll(pageData,page-1,size);
        pageData.put("total",count);
        pageData.put("rows", systemConfigs);
        return pageData;
    }

    @RequestMapping(value = "/column-save/{id}")
    public String columnSave(@PathVariable("id") String id){
        PageData pd = this.getPageData();
        SystemColumnEntity systemColumnEntity = systemColumnService.findById(Integer.valueOf(id));
        if(null!=pd.get("tableName")&&!"".equals(pd.getString("tableName"))){
            systemColumnEntity.setTableName(pd.getString("tableName"));
        }
        if(null!=pd.get("className")&&!"".equals(pd.getString("className"))){
            systemColumnEntity.setClassName(pd.getString("className"));
        }
        if(null!=pd.get("deleteFlag")&&!"".equals(pd.getString("deleteFlag"))){
            systemColumnEntity.setDeleteFlag(pd.getString("deleteFlag"));
        }
        if(null!=pd.get("exportTitle")&&!"".equals(pd.get("exportTitle").toString())){
            systemColumnEntity.setExportTitle(pd.get("exportTitle").toString());
        }
        if(null!=pd.get("exportSheet")&&!"".equals(pd.get("exportSheet").toString())){
            systemColumnEntity.setExportSheet(pd.get("exportSheet").toString());
        }
        //表示新增
        try {
            Class clazz = Class.forName(ConsoleConstant.ENTITY_BASE_PATH + pd.getString("className"));
            List<String> strings = EntityAttributeUtil.entityAttribute(clazz);
            String allName = "";
            for(String str :strings){
                allName += str + " ";
            }
            systemColumnEntity.setAllName(allName.trim());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        systemColumnService.save(systemColumnEntity);
        return "success";
    }

    @RequestMapping(value = "/column-set-save/{id}")
    public String columnSetSave(@PathVariable("id") String id){
        PageData pd = this.getPageData();
        SystemColumnEntity systemColumnEntity = systemColumnService.findById(Integer.valueOf(id));
        String[] split = systemColumnEntity.getAllName().split(" ");
        StringBuilder freezeColumnSB = new StringBuilder();
        StringBuilder hiddenColumnSB = new StringBuilder();
        //存列头
        for(int i=0;i<split.length;i++){
            //冻结列 on--表示不冻结
            if(null!=pd.get(split[i])&&!"".equals(pd.getString(split[i]))){
                if(pd.getString(split[i]).equals("on")){
                    freezeColumnSB.append(split[i]+" ");
                }
            }
            //是否显示 on--表示显示
            if(null!=pd.get(split[i]+"_display")&&!"".equals(pd.getString(split[i])+"_display")){
                //隐藏
                if(pd.getString(split[i]+"_display").equals("on")){
                    hiddenColumnSB.append(split[i]+" ");
                }
            }
        }
        String clazz = systemColumnEntity.getClassName();
        PageData fields = new PageData();
        fields.put("tableName", clazz);
        List<SystemFieldEntity> all = systemFieldService.findAll(fields);
        for(SystemFieldEntity s : all){
            systemFieldService.deleteById(s.getId());
        }
        //存说明
        for(int i=0;i<split.length;i++){
            String key = split[i] + "_desc";
            String constraint = split[i] + "_typeConstraint";
            String formate = split[i] + "_format";
            String export =  split[i] + "_export";
            String merge =  split[i] + "_merge";

            SystemFieldEntity systemFieldEntity = new SystemFieldEntity();
            systemFieldEntity.setFieldEn(split[i]);
            if(null!=pd.get(key)&&!"".equals(pd.getString(key))){
                systemFieldEntity.setFieldCn(pd.getString(key));
                systemFieldEntity.setTypeConstraint(pd.getString(constraint));
                systemFieldEntity.setIsFormatter(pd.getString(formate));
                systemFieldEntity.setIsExport(pd.getString(export)==null?"N":"Y");
                systemFieldEntity.setIsMerge(pd.getString(merge)==null?"N":"Y");
            }else{
                systemFieldEntity.setFieldCn(split[i]);
                systemFieldEntity.setTypeConstraint("0");
                systemFieldEntity.setIsFormatter("N");
                systemFieldEntity.setIsExport("N");
                systemFieldEntity.setIsMerge("N");
            }
            systemFieldEntity.setTableName(systemColumnEntity.getClassName());
            systemFieldService.save(systemFieldEntity);
        }

        systemColumnEntity.setFreezeName(freezeColumnSB.toString().trim());
        systemColumnEntity.setHiddenName(hiddenColumnSB.toString().trim());
        systemColumnService.save(systemColumnEntity);
        return "success";
    }

    @RequestMapping(value = "/global-save")
    public String globalSave(){

        PageData pageData = this.getPageData();
        List<SystemGlobalEntity> all = systemGlobalService.findAll();
        SystemGlobalEntity systemGlobalEntity = null;
        //新建
        if(0==all.size()){
            systemGlobalEntity = new SystemGlobalEntity();
        }else if (1<all.size()){
            systemGlobalService.deleteAll();
            systemGlobalEntity = new SystemGlobalEntity();
        }else{
            systemGlobalEntity = all.get(0);
        }
        if(null!=pageData.get("globalNetName")&&!"".equals(pageData.getString("globalNetName"))){
            systemGlobalEntity.setGlobalNetName(pageData.getString("globalNetName"));
        }
        if(null!=pageData.get("globalCopyright")&&!"".equals(pageData.getString("globalCopyright"))){
            systemGlobalEntity.setGlobalCopyright(pageData.getString("globalCopyright"));
        }
        if(null!=pageData.get("globalICP")&&!"".equals(pageData.getString("globalICP"))){
            systemGlobalEntity.setGlobalICP(pageData.getString("globalICP"));
        }
        if(null!=pageData.get("globalShortNetName")&&!"".equals(pageData.getString("globalShortNetName"))){
            systemGlobalEntity.setGlobalShortNetName(pageData.getString("globalShortNetName"));
        }
        if(null!=pageData.get("globalPermitIPs")&&!"".equals(pageData.getString("globalPermitIPs"))){
            systemGlobalEntity.setGlobalPermitIPs(pageData.getString("globalPermitIPs"));
        }
        systemGlobalService.save(systemGlobalEntity);
        return "success";
    }
}
